package com.pai4j.act.controller;
import com.pai4j.act.service.CommentService;
import com.pai4j.common.bean.PAIPageResponseBeanUtil;
import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.common.enums.BaseErrCodeEnum;
import com.pai4j.common.enums.ResponseCodeEnum;
import com.pai4j.common.helper.SessionHelper;
import com.pai4j.domain.vo.request.request.CommentSaveVO;
import com.pai4j.domain.vo.response.CommentResponseVO;
import com.pai4j.domain.vo.response.UserBaseResponseInfoVO;
import com.pai4j.log.annotation.OperationLog;
import com.pai4j.remote.act.ICommentClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;


@RestController
public class CommentController implements ICommentClient {


    @Autowired
    private CommentService commentService;

    /**
     * 保存评论
     * @param vo
     * @return
     */
    @OperationLog(
        module = "评论管理",
        operation = "发表评论",
        description = "用户发表评论",
        recordParams = true
    )
    public PAIResponseBean<Long> saveComment(@RequestBody CommentSaveVO vo) {
        Long commentId = commentService.saveComment(vo);
        return PAIResponseBeanUtil.success(commentId);
    }

    /**
     * 删除评论
     * @return
     */
    @OperationLog(
        module = "评论管理",
        operation = "删除评论",
        description = "用户删除评论",
        recordParams = true
    )
    public PAIResponseBean deleteComment(@PathVariable Long id, @PathVariable String userId) {
        commentService.deleteComment(id, userId);
        return PAIResponseBeanUtil.success();
    }


    /**
     * 置顶评论
     * @param commentId
     * @return
     */
    public PAIResponseBean<Long> topComment(@PathVariable Long commentId) {
        commentService.topComment(commentId);
        return PAIResponseBeanUtil.success("OK");
    }

    /**
     * 取消置顶评论
     * @param commentId
     * @return
     */
    public PAIResponseBean<Long> cancelTopComment(@PathVariable Long commentId) {
        commentService.cancelTopComment(commentId);
        return PAIResponseBeanUtil.success("OK");
    }

    /**
     * 查询评论列表
     * @param resourceId
     * @param resourceType
     * @param content
     * @param isHot
     * @param isNew
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PAIPageResponseBeanUtil<List<CommentResponseVO>> queryComments(@RequestParam(value = "resourceId", required = false) Long resourceId,
                                                                          @RequestParam(value = "resourceType", required = false) String resourceType,
                                                                          @RequestParam(value = "content", required = false) String content,
                                                                          @RequestParam(value = "isHot", required = false, defaultValue = "false") Boolean isHot,
                                                                          @RequestParam(value = "isNew", required = false, defaultValue = "false") Boolean isNew,
                                                                          @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                                                          @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        return commentService.queryCommentByCondition(content, resourceId, resourceType, pageNo, pageSize, isHot, isNew);
    }


    /**
     * 批量查询评论数量（走缓存）
     * 该接口支持批量查询多个资源的评论数量，通过Redis缓存提高查询性能
     * 
     * @param resourceIds 资源ID列表，不能为空
     * @param resourceType 资源类型，支持MOMENT、ARTICLE、COURSE等
     * @return 资源ID与评论数量的映射关系
     */
    @OperationLog(
        module = "评论管理",
        operation = "批量查询评论数量",
        description = "批量查询资源评论数量（缓存优化）",
        recordParams = true
    )
    @PostMapping("/act-service/comment/count/batch")
    public PAIResponseBean<java.util.Map<Long, Long>> batchCount(@RequestBody List<Long> resourceIds,
                                                                 @RequestParam("resourceType") String resourceType) {
        // 参数校验
        if (resourceIds == null || resourceIds.isEmpty()) {
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(), "资源ID列表不能为空");
        }
        
        if (resourceIds.size() > 100) {
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"单次查询资源数量不能超过100个");
        }
        
        // 过滤掉无效的资源ID
        List<Long> validResourceIds = resourceIds.stream()
                .filter(Objects::nonNull)
                .filter(id -> id > 0)
                .distinct()
                .collect(Collectors.toList());
        
        if (validResourceIds.isEmpty()) {
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"没有有效的资源ID");
        }
        
        return commentService.batchCountFromCache(validResourceIds, resourceType);
    }

    /**
     * 获取资源点赞人头像列表
     * 该接口用于前端展示某个资源的点赞用户头像，支持分页查询
     * 
     * @param resourceId 资源ID
     * @param resourceType 资源类型（MOMENT、ARTICLE、COURSE等）
     * @param pageNo 页码，默认第1页
     * @param pageSize 每页大小，默认10个，最大50个
     * @return 点赞用户的头像和基本信息列表
     */
    @OperationLog(
        module = "互动管理",
        operation = "查询点赞人列表",
        description = "查询资源点赞用户头像列表",
        recordParams = true
    )
    @GetMapping("/act-service/like/users")
    public PAIResponseBean<List<UserBaseResponseInfoVO>> getLikeUsers(
            @RequestParam("resourceId") Long resourceId,
            @RequestParam("resourceType") String resourceType,
            @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        
        // 参数校验
        if (resourceId == null || resourceId <= 0) {
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"资源ID不能为空且必须大于0");
        }
        
        if (StringUtils.isBlank(resourceType)) {
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"资源类型不能为空");
        }
        
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        
        if (pageSize == null || pageSize < 1 || pageSize > 50) {
            pageSize = 10;
        }
        
        return commentService.getLikeUsersByResource(resourceId, resourceType, pageNo, pageSize);
    }

}
